package com.xizi.forum.controller;

import com.xizi.forum.common.AppResult;
import com.xizi.forum.common.Constants;
import com.xizi.forum.common.ResultCode;
import com.xizi.forum.exception.ApplicationException;
import com.xizi.forum.model.ArticleInfo;
import com.xizi.forum.model.UserInfo;
import com.xizi.forum.service.IArticleInfoService;
import com.xizi.forum.utils.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

// 帖子模块
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleInfoController {

    @Autowired
    private IArticleInfoService articleInfoService;

    /**
     * 创建帖子
     * @param request
     * @param boardId 板块id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return
     */
    @RequestMapping(value = "/create",method = RequestMethod.POST,produces = "application/json")
    public AppResult create(HttpServletRequest request,long boardId, String title, String content){
        //1.校验用户是否登入
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constants.USERINFO) == null){
            log.info("session 为空！用户未登入，不能新增帖子。");
            throw new ApplicationException(ResultCode.FAILED_NOT_LOGIN);
        }
        //2.构建创建帖子对象
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USERINFO);
        long userId = userInfo.getId();
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setUserId(userId);
        articleInfo.setBoardId(boardId);
        articleInfo.setTitle(title);
        articleInfo.setContent(content);

        AppResult appResult = articleInfoService.insertArticle(articleInfo);
        return appResult;
    }

    /**
     * 获取当前版块下的所有帖子
     * @param boardId 版块id
     * @return
     */
    @RequestMapping(value = "/getAllByBoardId",method = RequestMethod.GET,produces = "application/json")
    public AppResult getAllByBoardId(Long boardId){
        List<ArticleInfo> boardInfos = null;

        if(boardId != null){//通过boardId 获取帖子
            if(boardId < 0){
                return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
            }
            boardInfos = articleInfoService.selectAllArticleByBoardId(boardId);
        }else {// 获取所有帖子 直接说：就是首页下的帖子
            boardInfos = articleInfoService.selectAllArticle();
        }
        if(boardInfos == null){
            boardInfos = new ArrayList<>();
        }
        log.info("返回的帖子列表 : {}" , boardInfos + ",板块  boardId :" + boardId);
        return AppResult.success(boardInfos);
    }

    /**
     * 获取帖子详情
     * @param request
     * @param id 帖子id
     * @return
     */
    @GetMapping("/getById")
    public AppResult getById(HttpServletRequest request ,@NonNull Long id){
        //1.参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.校验用户是否登入
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constants.USERINFO) == null){
            throw new ApplicationException(ResultCode.FAILED_UNAUTHORIZED);
        }
        //3.校验帖子状态
        ArticleInfo articleInfo = articleInfoService.selectArticleById(id);
        if(articleInfo == null){
            log.warn("articleInfo 为 null ！");
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS);
        }

        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
        Long curUserId = userInfo.getId();

        if(articleInfo.getUserId() == curUserId){
            articleInfo.setOwn(true);
        }
        log.info("articleInfo : {}",articleInfo);
        return AppResult.success(articleInfo);
    }

    /**
     * 修改帖子
     * @param id 帖子id
     * @param title 帖子标题
     * @param content 帖子内容
     * @return
     */
    @PostMapping("/modify")
    public AppResult modify(@NonNull Long id,@NonNull String title,@NonNull String content){
        //1. 参数校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2. 创建修改帖子对象
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setId(id);
        articleInfo.setTitle(title);
        articleInfo.setContent(content);
        Boolean check = articleInfoService.updateArticleById(articleInfo);

        return AppResult.success();
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(@NonNull Long id){
        //1. 参数校验
        if(id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Boolean check = articleInfoService.updateLike(id);
        return AppResult.success();
    }

    /**
     * 删除帖子（逻辑删除）
     * @param id 帖子id
     * @return
     */
    @PostMapping("/delete")
    public AppResult delete(@NonNull Long id){
        //1. 参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Boolean check = articleInfoService.deleteArticle(id);
        return AppResult.success();
    }

    /**
     * 通过用户id 获取 用户发布的所有帖子
     * @param request
     * @param userId 用户id
     * @return
     */
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId(HttpServletRequest request,Long userId){
        log.info("userId : {}", userId);
        List<ArticleInfo> list = null;
        if(userId == null){ // 当前登入用户发布帖子信息
            HttpSession session = request.getSession(false);
            UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USERINFO);
            userId = userInfo.getId();
            list = articleInfoService.getAllByUserId(userId);
            for (ArticleInfo articleInfo:list) {
                articleInfo.setOwn(true);
            }
        }else {// 其他用户发布帖子信息
            // 根据userId 来查询
            list = articleInfoService.getAllByUserId(userId);
        }
        return AppResult.success(list);
    }

}
